<template>
  <div class="condition-container">
    <div class="condition-head">
      <el-row :gutter="20" justify="start" align="middle">
        <el-col :span="2">
          <img src="@/assets/images/img_condition.png" style="width: 40px;height:40px" alt="">
        </el-col>
        <el-col :span="12">
          <el-text size="large">AI智能助手</el-text>
        </el-col>
      </el-row>
      <el-row :gutter="20" justify="start" align="middle">
        <el-col :span="24">
          <el-text type="info">
            Al助手可根据自主选定的工单数据的参与人、时间范围（本月/本季度/本年）以及工单状态（未完成/进行中） 对工单数据进行智能分析，为提升工单处理效率提供有力支持。
          </el-text>
        </el-col>

      </el-row>
    </div>
    <div class="condition-body" ref="aiListContainer">
      <div class="chat-container">
        <div class="chat-row" v-for="(item, index) in chatArr" :key="index"
          :class="item.role === 'customer' ? 'customer-chat-row' : ''">
          <div class="message-box" :class="item.role === 'customer' ? 'customer-message-box' : 'ai-message-box'">
            <span v-html="item.content"></span>
            <i v-if="item.role === 'ai' && index === chatArr.length - 1 && running === true"
              class="iconfont icon-gengduo fade-element" style="color:#606266"></i>
            <div v-if="item.role === 'ai'" style="margin-top: 10px;" class="status-row">
              <span>{{ item.status }}</span>
              <i v-if="item.status === '回答完成'" class="iconfont icon-completed"
                style="color: #67C23A;margin-left: 5px;font-size: 12px;"></i>
            </div>

          </div>



        </div>

      </div>

    </div>
    <div class="condition-footer" v-loading="isLoading">
      <div class="filter-top">
        <el-text>筛选</el-text>
      </div>
      <div class="filter-body">
        <el-row :gutter="20" justify="start" align="middle">
          <el-col :span="8" v-for="(item, index) in fieldArr" :key="index">
            <cinput :item="item" :handleChange="handleChange"></cinput>
          </el-col>
        </el-row>

      </div>
      <div class="filter-footer">
        <div class="filter-submit">
          <el-icon><i style="cursor: pointer;" class="iconfont icon-xiangshang2" @click="handleSubmit"></i></el-icon>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import Cookies from 'js-cookie';
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { apiConfigurable, apiUploadFile } from "@/request/api";
import { ref, onMounted, watch, computed, nextTick } from "vue";
import { useRoute } from "vue-router"
const route = useRoute()
const query = route.query
import { ElMessage, ElMessageBox } from "element-plus";

import cinput from "@/components/input/input.vue"


import emitter from '@/utils/emitter'
import { chatItemVO, fileItemVO, uploadFileVO } from "@/interface/interface"

const aiListContainer = ref<HTMLDivElement | null>(null)

const isLoading = ref(false)
function handleLoading(value) {
  isLoading.value = value
}

const fieldArr = ref([])
const chatArr = ref<chatItemVO[]>([]);
const running = ref(false);

const reportid = ref<string | string[]>('');
const cookie = ref<string | string[]>('');

// reportid.value = route.query.reportid || ''
// cookie.value = route.query.token || ''




const user = ref("abc-123");

onMounted(() => {
  // nextTick(()=>{
  //   getData()
  // })
});

watch(()=>route.query,(val)=>{
  console.log("update",val)
  if(val){
    getData()
  }

},{
  // immediate:true
})

function getData() {

  const data = {
    // reportid:'16463013835381102243127076437903'
  }
  
  const {reportid} = route.query



  const url = `/myreport.apiresult.do?ui_key=listview&reportid=${route.query.reportid}`;
 
  // const url = `/capi/myreport.apiresult.do?reportid=16463013835381102243127076437903&ui_key=listview`;

  isLoading.value = true
  apiConfigurable(url, data, "post").then(res => {
    if (res.status === 200) {
      fieldArr.value = res.data.reportFilterField
    }

  }).finally(() => {
    isLoading.value = false
  })

}

function handleChange(item, value) {
  item.value = value
}


function handleSubmit() {



  const token = "app-jGeSOWYwUcdXIrYVvaYkYZ4c";


  const data = {

    inputs: {
      query: "分析数据",//话术
      cookie: route.query.token || '',
      category: route.query.reportid || '',
      urlencoded: ""
    },
    response_mode: "streaming",
    files: [],
    user: user.value,

  };
  const obj = {}
  let content = ""
  console.log("data",data)

  for (let i = 0; i < fieldArr.value.length; i++) {
    const fieldItem = fieldArr.value[i]
    obj[`${i}_report_fieldid`] = fieldItem['fieldID']
    obj[`${i}_report_operate`] = fieldItem['operate']
    obj[`${i}_report_value`] = fieldItem['value']
    content += `${fieldItem.title} <span style="color:green">${fieldItem.value || '空'};</span> `
  }

  chatArr.value.push({
    role: "customer",
    content: content,
    type: "text",
  });


  // 触底
  nextTick(() => {
    aiListContainer.value.scrollTop = aiListContainer.value.scrollHeight;
  })



  data.inputs.urlencoded = new URLSearchParams(obj).toString();

  chatArr.value.push({ role: "ai", content: "", type: "text", status: "处理中..." });
  running.value = true;



  fetchEventSource("/api/v1/workflows/run", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(data),
    onmessage(event) {

      if (!event.data) {
        return
      }
      const res = JSON.parse(event.data);
  



      const content = chatArr.value[chatArr.value.length - 1].content;

      switch (res.event) {
        case "workflow_started":

          break;

        case "node_started":

          break;

        case "text_chunk":


          let htmlText = res.data.text.replace(/\n/g, "<br/>");

          chatArr.value[chatArr.value.length - 1].content = content + htmlText;
          chatArr.value[chatArr.value.length - 1].status = "正在回答中..."
          aiListContainer.value.scrollTop = aiListContainer.value.scrollHeight;
          break;

        case "node_finished":

          break;

        case "workflow_finished":
          running.value = false;
          chatArr.value[chatArr.value.length - 1].status = "回答完成"
          break;
      }

      emitter.emit("scrollToBottom")
    },
    onclose() {
      console.log("close");
    },
    onerror(error) {
      console.log("error", error);
      throw error
    },
  });
}


function extractBetweenChars(str, startChar, endChar) {
  // const regex = new RegExp(`${startChar}(.*?)${endChar}`, 's'); // 使用非贪婪匹配
  const regex = new RegExp(/(\!\[image\]\()(.*?)(\))/, 's');

  const match = str.match(regex);
  return match ? match[2] : null; // 返回匹配到的内容，如果没有匹配到则返回null
}

function handleSearch() {

  const data = {}
  const url = `/capi/myreport.apiresult.do?view=1&ui_nextform=formdata&proc=&ui_key=showpicture`;

  data['reportid'] = '84D114BCCC0E4B64B4C202412191344'
  for (let i = 0; i < fieldArr.value.length; i++) {
    const fieldItem = fieldArr.value[i]
    data[`${i}_report_fieldid`] = fieldItem['fieldID']
    data[`${i}_report_operate`] = fieldItem['operate']
    data[`${i}_report_value`] = fieldItem['value']
  }


  isLoading.value = true
  apiConfigurable(url, data, "post").then(res => {
    if (res.status === 200) {

    }

  }).finally(() => {
    isLoading.value = false
  })

}











</script>

<style>
.condition-container {
  padding: 10px;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  justify-content: space-between;

}

.condition-container .condition-head {
  width: 100%;
  height: 100px;
  flex-grow: 0;
  flex-shrink: 0;
  border-bottom: 1px solid #EBEEF5;
}

.condition-container .condition-body {
  flex-grow: 1;
  flex-shrink: 1;
  overflow: scroll;
  min-height: 200px;
  /* background-color: aquamarine; */
}

.condition-container .condition-footer {
  width: 98%;
  height: 250px;
  margin: 10px auto;
  flex-grow: 0;
  flex-shrink: 0;
  border-radius: 10px;
  border: 1px solid #EBEEF5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

}



.filter-top {
  width: 100%;
  height: 40px;
  background-color: #EBEEF5;
  padding-left: 10px;
  line-height: 40px;
  flex-grow: 0;
  flex-shrink: 0;
}

.filter-body {
  box-sizing: border-box;
  padding: 10px;
  flex-grow: 1;
  flex-shrink: 1;
  overflow: scroll;

}

.filter-footer {
  width: 100%;
  height: 40px;
  flex-grow: 0;
  flex-shrink: 0;
  background-color: #fff;
  line-height: 40px;
  text-align: right;
  border-top: 1px solid #EBEEF5;
  display: flex;
  align-items: center;
  justify-content: flex-end;

}


.filter-lable {
  margin: 15px auto 5px;
  padding-left: 5px;

}

.filter-submit {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #0052cc;
  border-radius: 50%;
  color: #fff;
  float: right;
  margin-right: 10px;
}



.chat-row {
  display: flex;
}

.customer-chat-row {
  justify-content: flex-end;
}


/* 应用动画到元素 */
.fade-element {
  animation: fadeInOut 2s infinite;
  /* 动画名称 持续时间 无限循环 */
}

/* 定义动画 */
@keyframes fadeInOut {

  0%,
  100% {
    opacity: 1;
    /* 完全不透明 */
  }

  50% {
    opacity: 0;
    /* 完全透明 */
  }
}

.status-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 10px;
  color: #909399;
}


.message-box {
  padding: 15px;
  background: #fff;
  border-radius: 10px;
  font-size: 14px;
  color: #606266;
}

.customer-message-box {
  max-width: 80%;

  background: #EBEEF5;
  color: #606266;
  border-radius: 20px 20px 0 20px;
  line-height: 26px;
  margin-top: 40px;
  margin-bottom: 40px;

}
</style>